import React, { Component , Fragment} from 'react';
import logo from './logo.svg';
import './App.css';
import TodoItem from "./TodoItem.js"
class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      inputValue :'',
      list:[]
    }
    this.handleInputValue = this.handleInputValue.bind(this);
    this.handleButtonClick = this.handleButtonClick.bind(this);
    this.handleItemDelete = this.handleItemDelete.bind(this);
  }
  render() {
    return (
      <Fragment>
      <div className="App">
        {/* 注释 */}
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
           <code>todolist</code>
        </p>
        <input value={this.state.inputValue} onChange={this.handleInputValue} />>
        <button onClick = {this.handleButtonClick}>提交</button>
        <code>{this.state.inputValue}</code>
        <ul>
          {this.getTodoItem()}
        </ul>
      </div>
      </Fragment>
    );
  }
  getTodoItem(){
    return this.state.list.map((item,index) =>{
      return <TodoItem key={index} value ={item} index ={index} deleteItem={this.handleItemDelete}/>
      // <li key={index} onClick={this.handleItemDelete.bind(this,index)}>{item}</li>
    })  
  }
  handleInputValue(e){
    const value = e.target.value;
    this.setState(() => ({
      inputValue:value
    }))
    // this.setState({
    //   inputValue:e.target.value
    // })
  }
  handleButtonClick(e){
    if(this.state.inputValue){
      this.setState((prevState) => ({
        list:[...prevState.list,prevState.inputValue],
        inputValue:''
     }))

    //   this.setState({
    //     list:[...this.state.list,this.state.inputValue],
    //     inputValue:''
    //  })
    }
  }
  handleItemDelete(index){
    //immutable
    //state 不允许我们直接操作做任何改变
    this.setState((prevState)=>{
      const list = [...prevState.list];
      list.splice(index,1)
      return {list}
    })
  }
}

export default App;
